/**
 *  MVVM 模式： M模型层，V层视图层，通过中间的VM中介层，同步数据。 M层的变动通知到VM层，VM层再次通知到V层；V层的变动，通过VM层通知到M层。
 */

const Web = {
    Model: function(type){
        const data = {
            'a': { name:'带我去带我去', age:15 },
            'b': { name:'dqwmlwdmq', age:16 },
            'default': { name:'', age: '' }
        }

        const changeData = (key,obj)=>{
            data[key] = obj

            this.VM().updateModelToView(key,obj)
        }
        const acceptViewChange = (newDom)=>{
            console.log(`Model接受到dom 的新值: ${newDom}`);
        }

        return {
            data: (data[type]||data.default),
            changeData,
            acceptViewChange,
        }
    },

    V: function(data={}){
        
        let dom = `<div> <h1>{{name}}</h1> <h2>{{age}}</h2> </div>`

        const changeView = (str)=>{
            dom = str
            this.VM().updateViewToModel(str)
        }
        const acceptModelChange = (key,obj)=>{
            console.log(`View接受到Model { ${key}: ${obj} } 的修改`);
        }
        
        const result = dom.replace(/\{\{(\w+)\}\}/g, function(subStr,group1){
            return data[group1]||''
        })

        return {
            dom: result,
            changeView,
            acceptModelChange,
        }
    },

    VM: function(){
        const updateModelToView = (key,obj)=>{ 
            // 转发
            this.V().acceptModelChange(key,obj)
        }

        const updateViewToModel = (domStr)=>{
            // 转发
            this.Model().acceptViewChange(domStr)
        }

        return {
            updateModelToView,
            updateViewToModel,
        }
    },
}


Web.Model().changeData('c','带我去你家就完全打开')
Web.V().changeView('<div> <p>{{c}}</p> </div>')